package com.stox.client.ui.javafx.chartingy.widget;

import java.util.List;

import javafx.event.EventHandler;
import javafx.scene.control.Label;
import javafx.scene.control.PopupControl;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.FlowPane;

import com.stox.client.ui.javafx.chartingy.model.plot.IndicatorPlot;
import com.stox.client.ui.javafx.chartingy.view.ChartingView;
import com.stox.client.ui.javafx.core.util.CSS;
import com.stox.client.ui.javafx.core.util.UI;
import com.stox.shared.indicator.manager.IndicatorManager;
import com.stox.shared.indicator.model.enumeration.IndicatorPosition;
import com.stox.shared.indicator.model.intf.Indicator;
import com.stox.shared.util.ApplicationContextUtil;

public class IndicatorChooserPopupControl extends PopupControl {

	private final ChartingView chartingView;
	private final FlowPane contentPane = new FlowPane();
	private final EventHandler<MouseEvent> eventHandler = new EventHandler<MouseEvent>() {
		@SuppressWarnings({"unchecked", "rawtypes"})
		@Override
		public void handle(final MouseEvent event) {
			hide();
			final Label label = (Label) event.getSource();
			final Indicator indicator = (Indicator) label.getUserData();
			final IndicatorPosition position = indicator.getPosition(indicator.createDefaultConfiguration());
			final IndicatorPlot plot = new IndicatorPlot(indicator);
			plot.setPosition(chartingView, position);
			plot.load();
			plot.getChart().updateAxisBounds();
		}
	};

	public IndicatorChooserPopupControl(final ChartingView chartingView) {
		this.chartingView = chartingView;
		UI.style(contentPane, CSS.stoxPopup, CSS.chooserPopupContentPane);
		setAutoHide(true);
		centerOnScreen();
		getScene().setRoot(contentPane);

		final IndicatorManager indicatorManager = ApplicationContextUtil.getApplicationContext().getBean(IndicatorManager.class);
		final List<Indicator<?, ?>> indicators = indicatorManager.findAll();
		for (final Indicator<?, ?> indicator : indicators) {
			final Label label = new Label(indicator.getDisplayName());
			UI.style(label, CSS.buttonMockingLabel);
			label.setUserData(indicator);
			label.setOnMousePressed(eventHandler);
			contentPane.getChildren().add(label);
		}
	}

}
